// 云函数入口文件
const cloud = require('wx-server-sdk')
cloud.init({ env: cloud.DYNAMIC_CURRENT_ENV }) // 使用当前云环境

const db = cloud.database()//引用云数据库
const canJu = db.collection("canju")
const account = db.collection("account")
const _ = db.command
// 云函数入口函数
// 残局函数
exports.main = async (event, context) => {
  const wxContext = cloud.getWXContext()
  try {
    let isCanPlay = await canJu.where({
      canPlay: true,
      win: false,
      level: _.lte(event.topCeng)
    }).get()
    let randomNum = Math.floor(Math.random() * isCanPlay.data.length)

    const alreadyPlay = isCanPlay.data[randomNum].playInfo.some(obj => obj.openid == wxContext.OPENID)

    let canJuInfo = {
      _id: isCanPlay.data[randomNum]._id,
      level: isCanPlay.data[randomNum].level,
      alreadyPlay:alreadyPlay
    }

    let author = await account.where({
      openid: isCanPlay.data[randomNum].openid
    }).get()

    canJuInfo.userInfo = author.data[0].userInfo

    return {
      code: 'ok',
      res: canJuInfo
    }
  } catch (error) {
    return {
      code: 'fail',
      res: null
    }
  }


}
